﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;

namespace Galaktika.BI.Silverlight.Controls.General
{
    public partial class CustomContextMenu : UserControl
    {
        public CustomContextMenu()
        {
            InitializeComponent();

            this.MouseEnter += new MouseEventHandler(CustomContextMenu_MouseEnter);
            this.MouseLeave += new MouseEventHandler(CustomContextMenu_MouseLeave);
        }

        void CustomContextMenu_MouseLeave(object sender, MouseEventArgs e)
        {
            resTimer.Begin();
        }

        void CustomContextMenu_MouseEnter(object sender, MouseEventArgs e)
        {
            resTimer.Stop();
        }

        Popup m_PopupControl = null;
        public Popup PopupControl
        {
            get {
                if (m_PopupControl == null)
                {
                    m_PopupControl = new Popup();
                    m_PopupControl.Child = this;
                    //this.LostFocus += new RoutedEventHandler(CustomContextMenu_LostFocus);
                }
                return m_PopupControl;
            }
        }

        //void CustomContextMenu_LostFocus(object sender, RoutedEventArgs e)
        //{
        //    IsDropDownOpen = false;
        //}

        public bool IsDropDownOpen
        {
            get
            {
                return PopupControl.IsOpen;
            }
            set
            {
                PopupControl.IsOpen = value;
            }
        }

        public void SetLocation(Point pos)
        {
            // Сдвижка чтобы курсор попал в область меню
            PopupControl.VerticalOffset = pos.Y - 5;
            PopupControl.HorizontalOffset = pos.X - 5;
        }

        public void AddMenuItem(ContextMenuItem item)
        {
            if(item != null)
            {
                itemsPanel.Children.Add(item);
                item.ItemClick += new EventHandler(item_ItemClick);
            }
        }

        public UIElementCollection Items
        {
            get {
                return itemsPanel.Children;
            }
        }

        public void AddMenuSplitter()
        {
            itemsPanel.Children.Add(new ContextMenuSplitter());
        }

        void item_ItemClick(object sender, EventArgs e)
        {
            IsDropDownOpen = false;
        }

        private void resTimer_Completed(object sender, EventArgs e)
        {
            IsDropDownOpen = false;
        }
    }
}
